﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Infinity.Expressions.Extension;

namespace Infinity.Expressions.Loops
{
	/// <summary>
	/// A while ciklus reprezentációja
	/// </summary>
	public class WhileLoop : Loop
	{
		public Expression Condition { get; set; }

		public override bool Step()
		{
			if (Condition != null)
			{
				return Condition.CompileExpression<Func<bool>>()();
			}
			else
			{
				return false;
			}
		}

		protected override Expression BodyExpression
		{
			get
			{
				if (Condition != null && this.Body != null)
				{
					LabelTarget breakLabel = Expression.Label("break");
					var breakExpression = Expression.Break(breakLabel);

					return Expression.Loop(
						Expression.IfThenElse(
										  Condition,
										  this.Body.ToExpression(),
										  Expression.Break(breakLabel)), breakLabel);
				}
				else return null;
			}
		}
	}
}
